package controller.recipe;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.recipe.dao.RecipeDao;
import model.recipe.dto.RecipeCmtDto;
import model.recipe.dto.RecipeDto;
import model.recipe.dto.StepDto;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import common.Constant;
import common.Page;

public class RecipeController extends MultiActionController {
	private RecipeDao recipeDao;
	public void setRecipeDao(RecipeDao recipeDao) {
		this.recipeDao = recipeDao;
	}

	// recipe_list.do
	public ModelAndView recipe_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//검색옵션
		String search_option = request.getParameter("search_option");
		if(search_option == null) search_option="multi";
		String search = request.getParameter("search");
		if(search == null) search="";
		
		//페이지 정보 설정
		int curPage = 1;
		if(request.getParameter("page")!= null){
			curPage = Integer.parseInt(request.getParameter("page"));
		}
		int count = recipeDao.recipeCount(search_option, search);
		Page page = new Page(count, curPage);
		int start = page.getPageBegin();
		int end = page.getPageEnd();
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		List<RecipeDto> list = recipeDao.recipeList(search_option, search, start, end);
		map.put("list", list);
		
		//페이지 네비게이션 문자열
		map.put("pageList", page.putPageRange());
		//현재페이지 번호
		map.put("curPage", curPage);
		map.put("count", count);
		//검색관련 변수 저장
		map.put("search_option", search_option);
		map.put("search", search);
		
		return new ModelAndView("/recipe/recipe_list.jsp", "map", map);
	}
	
	//recipe_write.do
	public ModelAndView recipe_write(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		
		List<String> list1 = recipeDao.callTypeList();
		map.put("type", list1);
		
		list1 = recipeDao.callIngredientList();
		map.put("ingredient", list1);
		
		List<Integer> list2 = recipeDao.callTimeList();
		map.put("time", list2);
		
		return new ModelAndView("/recipe/recipe_write.jsp", "map", map);
	}
	
	//recipe_insert.do
	public String recipe_insert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// Final image 파일업로드 처리
		//request 객체를 MultipartRequest로 변환
		MultipartRequest multi = (MultipartRequest)request;
		MultipartFile final_img = multi.getFile("final_img");
		String filename = final_img.getOriginalFilename();
		
		int next_idx = recipeDao.maxRecipeIdx();
		
		if(!final_img.isEmpty()){
			String path = Constant.path_recipe_janghyunny+next_idx+"\\";	//파일을 업로드할 경로
			File f = new File(path+filename);
			if( !f.exists()){
				f.mkdirs(); // 디렉터리 생성				
			}
			final_img.transferTo(f);
		}
				
		//recipe 테이블에 저장
		RecipeDto recipeDto = new RecipeDto();
		
		recipeDto.setUserid(request.getParameter("userid"));
		recipeDto.setSubject(request.getParameter("subject"));
		recipeDto.setHistory(request.getParameter("history"));
		recipeDto.setType(request.getParameter("type"));
		recipeDto.setIngredient(request.getParameter("ingredient"));
		recipeDto.setTime(Integer.parseInt(request.getParameter("time")));
		recipeDto.setIngredients(request.getParameter("ingredients"));
		recipeDto.setCooker(request.getParameter("cooker"));
		recipeDto.setImage(filename);
		
		recipeDao.recipeInsert(recipeDto);
		
		//step 테이블에 저장
		int count = Integer.parseInt(request.getParameter("count"));
		
		StepDto stepDto = new StepDto();
		
		for(int i=1; i<count; i++){
			// Final image 파일업로드 처리
			//request 객체를 MultipartRequest로 변환
			//MultipartRequest submulti = (MultipartRequest)request;
			MultipartFile subImg = multi.getFile("subImg_"+i);
			String subfilename = subImg.getOriginalFilename();
			
			if(!subImg.isEmpty()){
				String path = Constant.path_step_janghyunny+next_idx+"\\";	//파일을 업로드할 경로
				File f = new File(path+subfilename);
				if( !f.exists()){
					f.mkdirs(); // 디렉터리 생성				
				}
				subImg.transferTo(f);
			}
			
			stepDto.setRecipe_idx(next_idx);
			stepDto.setStep(i);
			stepDto.setImportant(request.getParameter("important_"+i));
			stepDto.setContent(request.getParameter("content_"+i));
			stepDto.setImage1(subfilename);
			
			recipeDao.stepInsert(stepDto);
		}
		
		return "redirect:/recipe/recipe_list.do";
	}
	
	//recipe_detail.do
	public ModelAndView recipe_detail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int idx = Integer.parseInt(request.getParameter("idx"));
		Map<String, Object> map = new HashMap<String, Object>();
		
		RecipeDto recipe_list = recipeDao.recipeDetail(idx);
		map.put("recipe_list", recipe_list);
		
		List<StepDto> step_list = recipeDao.stepDetail(idx);
		map.put("step_list", step_list);
		
		map.put("idx", idx);
		
		//조회수 증가
		HttpSession session = request.getSession();
		String userid = (String)session.getAttribute("userid"); //로그인한 USERID
		if(userid == null) userid="";
		String recipe_list_userid = recipe_list.getUserid();
		if(!(userid.equals(recipe_list_userid))){	//로그인한 USERID와 게시물글 USERID가 다르면 조회수를 증가시킨다. (본인글은 HitUp 안됨.)
			recipeDao.recipeHitUp(idx);
		}
		
		//덧글 리스트
		List<RecipeCmtDto> cmt_list = recipeDao.recipeCmtList(idx);
		
		map.put("cmt_list", cmt_list);		
		
		return new ModelAndView("/recipe/recipe_detail.jsp", "map", map);
	}
	
	//recipe_edit_view.do
	public ModelAndView recipe_edit_view(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		int idx = Integer.parseInt(request.getParameter("idx"));
		Map<String, Object> map = new HashMap<String, Object>();
		
		RecipeDto recipe_list = recipeDao.recipeDetail(idx);
		map.put("recipe_list", recipe_list);
		
		List<StepDto> step_list = recipeDao.stepDetail(idx);
		map.put("step_list", step_list);
		
		List<String> list1 = recipeDao.callTypeList();
		map.put("type", list1);
		
		list1 = recipeDao.callIngredientList();
		map.put("ingredient", list1);
		
		List<Integer> list2 = recipeDao.callTimeList();
		map.put("time", list2);
		
		map.put("idx", idx);
		
		return new ModelAndView("/recipe/recipe_edit.jsp", "map", map);
	}
	
	//recipe_edit.do
		public String recipe_edit(HttpServletRequest request, HttpServletResponse response) throws Exception {
			// Final image 파일업로드 처리
			//request 객체를 MultipartRequest로 변환
			MultipartRequest multi = (MultipartRequest)request;
			MultipartFile final_img = multi.getFile("final_img");
			String filename = final_img.getOriginalFilename();
			
			int idx = Integer.parseInt(request.getParameter("idx"));
			
			if(!final_img.isEmpty()){
				String path = Constant.path_recipe_janghyunny+idx+"\\";	//파일을 업로드할 경로
				File f = new File(path+filename);
				if( !f.exists()){
					f.mkdirs(); // 디렉터리 생성				
				}
				final_img.transferTo(f);
			}
					
			//recipe 테이블에 저장
			RecipeDto recipeDto = new RecipeDto();
			
			recipeDto.setIdx(idx);
			recipeDto.setUserid(request.getParameter("userid"));
			recipeDto.setSubject(request.getParameter("subject"));
			recipeDto.setHistory(request.getParameter("history"));
			recipeDto.setType(request.getParameter("type"));
			recipeDto.setIngredient(request.getParameter("ingredient"));
			recipeDto.setTime(Integer.parseInt(request.getParameter("time")));
			recipeDto.setIngredients(request.getParameter("ingredients"));
			recipeDto.setCooker(request.getParameter("cooker"));
			recipeDto.setImage(filename);
			
			recipeDao.recipeUpdate(recipeDto);
			
			//step 테이블에 저장
			int count = Integer.parseInt(request.getParameter("count"));
			int disCount =   recipeDao.stepCount(idx);	//
			System.out.println(idx);
			System.out.println("disCount :"+disCount);
			StepDto stepDto = new StepDto();
			
			//업데이트처리
			for(int i=1; i<=disCount; i++){
				// Final image 파일업로드 처리
				//request 객체를 MultipartRequest로 변환
				//MultipartRequest submulti = (MultipartRequest)request;
				MultipartFile subImg = multi.getFile("subImg_"+i);
				String subfilename = subImg.getOriginalFilename();
				
				if(!subImg.isEmpty()){
					String path = Constant.path_step_janghyunny+idx+"\\";	//파일을 업로드할 경로
					File f = new File(path+subfilename);
					if( !f.exists()){
						f.mkdirs(); // 디렉터리 생성				
					}
					subImg.transferTo(f);
				}
				
				stepDto.setRecipe_idx(idx);
				stepDto.setStep(i);
				stepDto.setImportant(request.getParameter("important_"+i));
				stepDto.setContent(request.getParameter("content_"+i));
				stepDto.setImage1(subfilename);
				
				
				recipeDao.stepUpdate(stepDto);
			}
			
			for(int i=(disCount+1); i<count; i++){
				// Final image 파일업로드 처리
				//request 객체를 MultipartRequest로 변환
				//MultipartRequest submulti = (MultipartRequest)request;
				MultipartFile subImg = multi.getFile("subImg_"+i);
				String subfilename = subImg.getOriginalFilename();
				
				if(!subImg.isEmpty()){
					String path = Constant.path_step_janghyunny+idx+"\\";	//파일을 업로드할 경로
					File f = new File(path+subfilename);
					if( !f.exists()){
						f.mkdirs(); // 디렉터리 생성				
					}
					subImg.transferTo(f);
				}
				
				stepDto.setRecipe_idx(idx);
				stepDto.setStep(i);
				stepDto.setImportant(request.getParameter("important_"+i));
				stepDto.setContent(request.getParameter("content_"+i));
				stepDto.setImage1(subfilename);
				
				
				recipeDao.stepInsert(stepDto);
			}
			
			return "redirect:/recipe/recipe_detail.do?idx="+idx;
		}
	
	//recipe_delete.do
	public String recipe_delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int idx = Integer.parseInt(request.getParameter("idx"));
		
		recipeDao.recipeDelete(idx);	//recipe테이블에서 게시물 삭제

		return "redirect:/recipe/recipe_list.do";
	}
	
	//recipe_cmtInsert.do
	public ModelAndView recipe_cmtInsert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int idx = Integer.parseInt(request.getParameter("idx"));
		String userid = request.getParameter("userid");
		String comment = request.getParameter("comment");
		int rate = Integer.parseInt(request.getParameter("star_choice_score"));
		
		RecipeCmtDto dto = new RecipeCmtDto();
		dto.setRecipe_idx(idx);
		dto.setUserid(userid);
		dto.setComment(comment);
		dto.setRate(rate);
		
		recipeDao.recipeCmtInsert(dto);	//덧글삽입
		
		//삽입후 다시 리스트 목록을 조회후 가져간다.
		List<RecipeCmtDto> cmt_list = recipeDao.recipeCmtList(idx);
		
		map.put("cmt_list", cmt_list);
		
		return new ModelAndView("/recipe/recipe_commentList.jsp", "map", map);
	}
	
	//recipe_cmtDelete.do
	public ModelAndView recipe_cmtDelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Map<String, Object> map = new HashMap<String, Object>();
		int idx = Integer.parseInt(request.getParameter("idx"));
		int cmtIdx = Integer.parseInt(request.getParameter("btnCmtIdx"));
		
		recipeDao.recipeCmtDelete(cmtIdx);	//덧글삭제
		
		//삽입후 다시 리스트 목록을 조회후 가져간다.
		List<RecipeCmtDto> cmt_list = recipeDao.recipeCmtList(idx);
		
		map.put("cmt_list", cmt_list);
		
		return new ModelAndView("/recipe/recipe_commentList.jsp", "map", map);
	}	
	
}
